import React, { Component } from 'react'
import Breadcrumb from '../../base/Breadcrumb'
import { withRouter } from 'react-router-dom'
import { Button, Input, Radio, Message, Table } from 'element-react'

class SkuCreated extends Component {
  constructor(props) {
    super(props)
    this.state = {
      id: this.props.match.params.id,
      name: sessionStorage.productName,
      list: [],
      skuList: [],
      useState: 0,
      sellState: 0,
      referencePrice: '',
      clearPrice: '',
      skuReferencePrice: 0,
      skuClearPrice: 0
    }
  }
  componentDidMount() {
    let list = JSON.parse(sessionStorage.skuArr)
    let n = list.length
    list.map((a, index) => {
      a.values.map((item, index1) => {
        item.input = 0
      })
    })
    console.log(list)
    this.setState({
      list
    })
    this.init()
  }
  init () {
    this.$ajax.getSkuList(this.props.match.params.id).then(res => {
      if (res.code === 200) {
        let skuList = res.data
        this.setState({skuList})
      }
    })
  }
  goEdit (a) {
    sessionStorage.skuName = a.name
    sessionStorage.skuId = a.id
    this.props.history.push(
      {
        pathname: `/skuCreatedOperate/${a.id}`,
        state: { fromDashboard: true }
      }
    )
  }
  goDetail (a) {
    sessionStorage.skuName = a.name
    sessionStorage.skuId = a.id
    this.props.history.push(
      {
        pathname: `/skuCreatedDetail/${a.id}`,
        state: { fromDashboard: true }
      }
    )
  }
  createSku () {
    let { referencePrice, clearPrice, name } = this.state
    if (!clearPrice || !referencePrice || !name) {
      Message('请输入完整信息')
      return
    }
    let skuName = this.state.name
    let id
    // 获取即将提交数组长度
    let length = 1
    this.state.list.map((a, index) => {
      length *= a.values.length
    })
    let arr = []
    for (let i = 0; i < this.state.list.length; i++) {
      arr.push(this.state.list[i].values)
    }
    // 存放id的数组
    var idArr = [[]]
    // 存放sku的数组
    var skuArr = [[]]
    // 存放金钱的数组
    var moneyArr = [[]]
    for (var i = 0; i < arr.length; i++) {
      var idArrT = []
      var skuArrT = []
      var moneyArrT = []
      for (var j = 0; j < idArr.length; j++) {
        for (var k = 0; k < arr[i].length; k++) {
          idArrT.push(idArr[j].concat(arr[i][k].id))
          skuArrT.push(skuArr[j].concat(arr[i][k].name))
          moneyArrT.push(moneyArr[j].concat(arr[i][k].input))
        }
      }
      idArr = idArrT
      skuArr = skuArrT
      moneyArr = moneyArrT
    }
    let data = []
    for (let i = 0; i< length; i++) {
      let money = 0
      moneyArr[i].forEach((a, index) => {
        money += Number(a)
      })
      let name = skuArr[i].join('/')
      data.push({
        id: this.state.id,
        clearPrice: Number(this.state.clearPrice) + money,
        referencePrice: Number(this.state.referencePrice) + money,
        specIds: idArr[i],
        name: this.state.name + '/' + name
      })
    }
    console.log(data)
    this.$ajax.createSku(data).then(res => {
      if (res.code === 200) {
        Message({
          message: '创建成功',
          type: 'success'
        })
        this.init()
      } else {
        Message.error('创建失败')
      }
    }).catch(() => {
      Message.error('网络错误')
    })
  }
  setInput (index, i, value) {
    let list = this.state.list
    list[index].values[i].input = value
    this.setState({
      list
    })
  }
  // 定价
  goSkuprice (a) {
    sessionStorage.skuName = a.name
    sessionStorage.skuId = a.id
    this.props.history.push({
      pathname: `/skuPrice/${a.id}`,
      state: { fromDashboard: true }
    })
  }
  setSellerState (a, i, value) {
    this.setState({[`sellState${i}`]: value})
    let data = {
      id: a.id,
      operation: 0,
      status: a.status,
      useStatus: parseInt(value)
    }
    this.$ajax.changeSkuState(data).then(res => {
      if (res.code === 200) {
        //
      } else {
        Message.error('网络错误')
      }
    }).catch(() => {
      Message.error('网络错误')
    })
  }
  setUserState (a, i, value) {
    this.setState({[`useState${i}`]: value})
    let data = {
      id: Number(a.id),
      operation: 1,
      status: Number(value),
      useStatus: Number(a.useStatus)
    }
    this.$ajax.changeSkuState(data).then(res => {
      if (res.code === 200) {
      } else {
        Message.error('修改失败')
      }
    }).catch(() => {
      Message.error('网络错误')
    })
  }
  render() {
    return (
      <div className="skuCreated">
        <Breadcrumb data={['商品管理', '商品规格', 'sku生成页']}/>
        <div className="height40"></div>
        <div className="inputGroup">
          <label className="inputLabel">产品名称：</label>
          <Input placeholder="请输入产品名称" className="inputSmall" size="large" onChange={name => {this.setState({name})}} value={this.state.name}/>
        </div>
        <div className="inputGroup">
          <label className="inputLabel">基准结算价格：</label>
          <Input placeholder="请输入基准结算价格" className="inputSmall" size="large" onChange={clearPrice => {this.setState({clearPrice})}}/>
        </div>
        <div className="inputGroup">
          <label className="inputLabel">基本参考价格：</label>
          <Input placeholder="请输入基本参考价格" className="inputSmall" size="large" onChange={referencePrice => {this.setState({referencePrice})}}/>
        </div>
        <div className="height20"></div>
        <table className="table">
          <tbody>
            <tr>
              <th>规格名称</th>
              <th>规格值</th>
              <th>附加价格</th>
            </tr>
            {this.state.list.map((a, index) => {
              let t = a.values.map((item, i) => {
                return (
                  <tr key={index + '/' + i}>
                  <td>{a.value}</td>
                  <td>{item.value}</td>
                  <td><Input className="inputSmall" value={this.state.list[index].values[i].input} onChange={this.setInput.bind(this, index, i)}/></td>
                </tr>
                )
              })
              return t
            })}

          </tbody>
        </table>
        <div className="height20"></div>
        <Button type="success" size="large" onClick={this.createSku.bind(this)}>生成sku</Button>
        <table className="table">
          <tbody>
            <tr>
              <th>sku名称</th>
              <th>参考价格</th>
              <th>结算价格</th>
              <th>库存</th>
              <th>单位</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
            {this.state.skuList.map((a, i) => {
              return (
                <tr key={i}>
                  <td>{a.name}</td>
                  <td>{a.referencePrice || '--'}</td>
                  <td>{a.clearPrice || '--'}</td>
                  <td>{a.repertoty || '--'}</td>
                  <td>{a.unit || '--'}</td>
                  <td>{a.status ? '已上架': '未上架'}</td>
                  <td>
                    <div>
                      <div className="inputGroup">
                        <div className="RadioGroup">
                          <Radio.Group value={this.state[`useState${i}`]} onChange={this.setUserState.bind(this, a, i)}>
                            <Radio value="1">可用</Radio>
                            <Radio value="0">不可用</Radio>
                          </Radio.Group>
                        </div>
                        <div className="RadioGroup">
                          <Radio.Group value={this.state[`sellState${i}`]} onChange={this.setSellerState.bind(this, a, i)}>
                            <Radio value="1">已上架</Radio>
                            <Radio value="0">未上架</Radio>
                          </Radio.Group>
                        </div>
                        <div><button className="btn btn-operate" onClick={this.goDetail.bind(this, a)}>查看</button></div>
                        <div><button className="btn btn-operate" onClick={this.goEdit.bind(this, a)}>编辑</button></div>
                        <div><button className="btn btn-operate" onClick={this.goSkuprice.bind(this, a)}>定价</button></div>
                      </div>
                    </div>
                  </td>
                </tr>
              )
            })}
          </tbody>
        </table>
      </div>
    )
  }
}

export default withRouter(SkuCreated)